package com.hmall.service;

import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.OSSClientUtil;
import com.hmall.mapper.*;
import com.hmall.model.*;
import com.hmall.util.EnvUtil;
import com.hdmall.business.common.util.HttpClientUtil;
import com.hmall.util.PdfUtil;
import com.hmall.vo.*;
import com.itextpdf.text.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.List;

@Slf4j
@Service
public class BackService {


    private  MallOrderFufillmentMapper mallOrderFufillmentMapper;

    private  SysCustomerMapper sysCustomerMapper;

    private  MallOrderMapper mallOrderMapper;

    private  MallOrderItemMapper mallOrderItemMapper;

    private  MallPaymentVoucherMapper mallPaymentVoucherMapper;

    private  SysUserDeptMapper sysUserDeptMapper;

    private  UserService userService;

    private  MallPriceMapper mallPriceMapper;

    private  MallProductMapper mallProductMapper;

    private  MallShippingMapper mallShippingMapper;

    private final SysUserMapper userMapper;

    @Lazy
    private  DealerService dealerService;

    private  MerchandiserService merchandiserService;

    private final JpushService jpushService;

    private OSSClientUtil ossClient=new OSSClientUtil();

    @Autowired
    public BackService(MallOrderFufillmentMapper mallOrderFufillmentMapper, SysCustomerMapper sysCustomerMapper, MallOrderMapper mallOrderMapper, MallOrderItemMapper mallOrderItemMapper, MallPaymentVoucherMapper mallPaymentVoucherMapper, SysUserDeptMapper sysUserDeptMapper, UserService userService, MallPriceMapper mallPriceMapper, DealerService dealerService, MallProductMapper mallProductMapper, MerchandiserService merchandiserService, MallShippingMapper mallShippingMapper, JpushService jpushService, SysUserMapper userMapper) {
        this.mallOrderFufillmentMapper = mallOrderFufillmentMapper;
        this.sysCustomerMapper = sysCustomerMapper;
        this.mallOrderMapper = mallOrderMapper;
        this.mallOrderItemMapper = mallOrderItemMapper;
        this.mallPaymentVoucherMapper = mallPaymentVoucherMapper;
        this.sysUserDeptMapper = sysUserDeptMapper;
        this.userService = userService;
        this.mallPriceMapper = mallPriceMapper;
        this.dealerService = dealerService;
        this.mallProductMapper = mallProductMapper;
        this.merchandiserService = merchandiserService;
        this.mallShippingMapper = mallShippingMapper;
        this.jpushService = jpushService;
        this.userMapper = userMapper;
    }

    //生成销售合同
    public ServerResponse createOrderFufillmentPDF(String mallOrderFufillmentIdStr, Integer customerId, String startTime, String endTime) throws FileNotFoundException, DocumentException {

        Integer thisYear = Integer.valueOf(startTime.split("-")[0]);
        Integer thisMonth = Integer.valueOf(startTime.split("-")[1]);
        Calendar calendar = Calendar.getInstance();
        calendar.set(thisYear, thisMonth - 1, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date voucherStartTime = calendar.getTime();
        calendar.set(Calendar.MONTH, thisMonth);
        Date voucherEndTime = calendar.getTime();

        List<Integer> mallOrderFufillmentIdList = new ArrayList<>();
        if(null == mallOrderFufillmentIdStr){
            mallOrderFufillmentIdList = mallOrderFufillmentMapper.selectIdList(customerId, voucherStartTime, voucherEndTime);
        }else {
            String str[] = mallOrderFufillmentIdStr.split(",", -1);
            for (int i = 0; i < str.length; i++) {
                mallOrderFufillmentIdList.add(Integer.valueOf(str[i]));
            }
        }

        //先封装成一个对象，进行pdf转换
        List<MallOrderFufillment> mallOrderFufillmentList = new ArrayList<>();
        SysCustomer customer = sysCustomerMapper.selectByPrimaryKey(customerId);
        if(0 != mallOrderFufillmentIdList.size()) {
             mallOrderFufillmentList= mallOrderFufillmentMapper.selectByIdList(mallOrderFufillmentIdList);
        }

        //总信息
        OrderFufillmentVo orderFufillmentVo = new OrderFufillmentVo();

        //甲方信息
        JiaInformation jiaInformation = new JiaInformation();

        jiaInformation.setBankName("中国工商银行义乌分行");
        jiaInformation.setBankNumber("1208020009049099922");
        jiaInformation.setCustomerName("义乌华鼎锦纶股份有限公司");
        jiaInformation.setCustomerPhone("0579-85261300");
        orderFufillmentVo.setJiaInformation(jiaInformation);
        //乙方信息
        YiInformation yiInformation = new YiInformation();


        yiInformation.setCustomerName(customer.getBusName());
        orderFufillmentVo.setYiInformation(yiInformation);

        //产品信息
        SendProduct sendProduct = new SendProduct();
        List<SendProductItem> sendProductItemList = new ArrayList<>();
        //不能批量查询

        BigDecimal allTotalPrice = new BigDecimal(0.0);
        BigDecimal allWeight = new BigDecimal(0.0);

        for(MallOrderFufillment fufillment : mallOrderFufillmentList){
            Long orderNo = mallOrderItemMapper.selectByPrimaryKey(fufillment.getOrderItemId()).getOrderNo();
            int orderItemId = fufillment.getOrderItemId();
            MallOrderItem mallOrderItem = mallOrderItemMapper.selectByOrderItemId(orderItemId);


            calendar = Calendar.getInstance();
            calendar.setTime(fufillment.getSendTime());
            String name = mallOrderItem.getProductName();
            String nameStr[] = name.split(",", -1);


            //封装成SendProductItem
            String sDateTime = calendar.get(Calendar.YEAR) + "-" + (calendar.getTime().getMonth() + 1) + "-" + calendar.getTime().getDate();
            String sType = nameStr[0];
            Long sOrderNo = orderNo;
            String sFineAndPore = nameStr[3] + nameStr[4];
            String sModel = nameStr[2];
            BigDecimal sWeight = fufillment.getWeight();
            BigDecimal sUnitPrice = mallOrderItem.getCurrentUnitPrice();
            BigDecimal sTotalPrice =  mallOrderItem.getCurrentUnitPrice().multiply(fufillment.getWeight());
            String sGrade = mallOrderItem.getGrade();
            SendProductItem sendProductItem = new SendProductItem(sDateTime, sOrderNo, sType, sFineAndPore, sModel, sGrade, sUnitPrice, sWeight, sTotalPrice);


            //总价
            allTotalPrice = allTotalPrice.add(sTotalPrice);
            //总重量
            allWeight = allWeight.add(fufillment.getWeight());
            sendProductItemList.add(sendProductItem);
        }


        sendProduct.setSendProductItemList(sendProductItemList);
        sendProduct.setAllTotalPrice(allTotalPrice);
        sendProduct.setAllWeight(allWeight);
        sendProduct.setStartTime(startTime);
        sendProduct.setEndTime(endTime);
        orderFufillmentVo.setSendProduct(sendProduct);


        List<Integer> customerUserIdList = sysUserDeptMapper.selectUserIdListByCustomerId(customer.getCustomerId());

        //1.表示通过的审核凭证
        List<MallPaymentVoucher> mallPaymentVoucher = new ArrayList<>();
        if(0 != customerUserIdList.size()) {
            mallPaymentVoucher = mallPaymentVoucherMapper.selectByCustomerUserIdListWithStatus(voucherStartTime, voucherEndTime, customerUserIdList, 1);
        }
        orderFufillmentVo.setMallPaymentVoucherList(mallPaymentVoucher);

        StatementOfAccountVo statementOfAccountVo = userService.getStatementOfAccountUp(customer.getCustomerId(), thisYear, thisMonth - 1).getData();
        orderFufillmentVo.setStatementOfAccountVo(statementOfAccountVo);


        UUID uuid = UUID.randomUUID();
        orderFufillmentVo.setOrderFufillmentName(uuid.toString() + ".pdf");

        //创建pdf

        //如果数据没有更新，不要更新pdf
        //定时任务是一分钟 so 当前时间 - 更新时间 < 1 min ?  update : noUpdate
        //为了防止其他改变，整体更新每天12点更新
        //1.发货历史 2.对账单
        int size = mallOrderFufillmentIdList.size();
        String pathPDF = "pdf";
        String pdfUrl = "";
        if(size != 0) {
            Date checkDate = mallOrderFufillmentList.get(size - 1).getCreateTime();
            Long changeTime = System.currentTimeMillis() - checkDate.getTime();
            Long oneMin = 1000 * 60L;

            Calendar nowCalendar = Calendar.getInstance();
            int hour = nowCalendar.get(Calendar.HOUR);
            int min = nowCalendar.get(Calendar.MINUTE);
            if (changeTime <= oneMin) {
                PdfUtil.createPDF(orderFufillmentVo);
            } else if (hour == 12 && min == 1) {
                PdfUtil.createPDF(orderFufillmentVo);
            }



            File pdfFile = new File(pathPDF);
            //可能有bug不会自动创建pdf目录
            if (!pdfFile.exists() && !pdfFile.isDirectory()) {
                // System.out.println("//不存在");
                pdfFile.mkdir();
            }
            //如果文件夹不存在则创建
            FileInputStream is = null;
            //系统字体不同
            String fileName = pathPDF + File.separator + orderFufillmentVo.getOrderFufillmentName();
            try {
                is = new FileInputStream(fileName);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //上传pdf
           pdfUrl = updatePDFHead(orderFufillmentVo.getOrderFufillmentName(), is);

            File PDFPath = new File(fileName);
            if (PDFPath.exists()) {
                PDFPath.delete();
            }
        }
        return ServerResponse.createBySuccess(pdfUrl);
    }

    public String updatePDFHead(String fileName,InputStream is)  {
        /*if (file == null || file.getSize() <= 0) {
            throw new Exception("文件不能为空");
        }*/
        String name = null;
        try {
            name = ossClient.uploadPdf2Oss(fileName,is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String imgUrl = ossClient.getImgUrl(name);
        //userDao.updateHead(userId, imgUrl);//只是本地上传使用的
        return imgUrl;
    }


    public ServerResponse createTestData(Integer customerUserId, Integer salesmanUserId, Integer merchUserId, List<Integer> typeList) throws InterruptedException {

        //创建收货地址
        MallShipping mallShipping = new MallShipping(null, customerUserId, "测试", "测试电话", "测试电话", "测试省份",
                "测试城市", "测试区/县", "测试地址", "测试邮编", null, new Date(), null, 0, 0, 0);
        mallShippingMapper.insert(mallShipping);
        Integer shippingId = mallShippingMapper.selectByUserId(customerUserId).get(0).getId();

        log.info("创建默认收货地址成功");

        Integer disCode = 2;


        //创建审核中订单
        if(typeList.contains(1)) {
            dealerService.createOrder(createProductListStr().get(1), null, customerUserId, shippingId, disCode, null);
            log.info("创建审核中订单成功");
        }
        //创建审核待发货订单
        if(typeList.contains(2)) {
            createHavePassOrder(customerUserId, salesmanUserId, merchUserId, shippingId);
            log.info("创建待发货订单成功");
        }
        //创建已经发过货的订单
        if(typeList.contains(3)) {
            createHaveSendOrder(customerUserId, salesmanUserId, merchUserId, shippingId);
            log.info("创建发过货的订单成功");
        }
        //创建交易完成订单
        if(typeList.contains(4)) {
            List<String> haveFinishOrder = createProductListStr();
            dealerService.createOrder(haveFinishOrder.get(1), null, customerUserId, shippingId, disCode, null);
            Long orderNo = mallOrderMapper.selectLatestOrderNo(customerUserId);
            mallOrderMapper.updateStatusByOrderNo(orderNo, 50);
            log.info("创建交易完成订单成功");
        }
        return ServerResponse.createBySuccess();
    }

    private List<String> createProductListStr(){
        Integer productMinId = mallProductMapper.selectMaxOrMinId("min");
        Integer productMaxId = mallProductMapper.selectMaxOrMinId("max");
        Integer productId = productMinId + (int) ((productMaxId - productMinId) * Math.random());
        String grade = mallPriceMapper.selectMaxGradeByProductId(productId);
        List<String> list = new ArrayList<>();
        list.add(productId.toString());
        String str = "[{\"productId\":" + productId + ",\"grade\":\"" + grade + "\",\"price\":100,\"weight\":100}]";
        list.add(str);
        return list;
    }


    private Long createHavePassOrder(Integer customerUserId, Integer salesmanUserId, Integer merchUserId, Integer shippingId) throws InterruptedException {

        Integer disCode = 2;
        List haveExamStr = createProductListStr();
        dealerService.createOrder((String) haveExamStr.get(1), null, customerUserId, shippingId, disCode, null);
        Long orderNo = mallOrderMapper.selectLatestOrderNo(customerUserId);

        Integer productId = Integer.parseInt((String) haveExamStr.get(0));
        String grade = mallPriceMapper.selectMaxGradeByProductId(productId);
        String model = mallProductMapper.selectByProductId(productId).getName().split(",")[2];
        String material = dealerService.getProductMaterialList(model).getData().get(0);
        //业务员审核通过
        String examStr = "[{\"materialVoList\":[{\"price\":\"10\",\"weight\":\"10\",\"materialCode\":\"" + material + "\"}]," + "\"grade\":\"" + grade + "\",\"productId\":\"" + haveExamStr.get(0) + "\"}]";
      //  dealerService.changeOrderStatus(salesmanUserId, orderNo, examStr, "通过", 1, "义乌华鼎锦纶股份有限公司", "二类销售", "客户支付", "其他");
        //跟单员审核通过
        merchandiserService.examOrder(merchUserId, orderNo, examStr, 1, "同意", new Date().toLocaleString(), null);
        return orderNo;
    }

    private void createHaveSendOrder(Integer customerUserId, Integer salesmanUserId, Integer merchUserId, Integer shipping) throws InterruptedException {

        Long orderNo = createHavePassOrder(customerUserId, salesmanUserId, merchUserId, shipping);
        Integer orderItemId = mallOrderItemMapper.selectByOrderNo(orderNo).get(0).getItemId();
        String sendStr = "[{\"orderItemId\":" + orderItemId + ",\"weight\":1}]";
        String fufillmentNo = getRandom(11);
        dealerService.sendOrder(sendStr, fufillmentNo, "测试地址");


    }

    private String getRandom(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return  val;
    }

    public ServerResponse ncFinishPush(String orderNo, String subOrderNo, Integer userId) throws IOException, ParseException {

        //nc推送默认10
        int status = 10;
        //极光推送 + pc推送
        jpushService.backPushMessage(userId, new Date(), status, orderNo + "-" + subOrderNo);
        log.info("极光推送成功");
        //短信服务
        String result = phoneMsgPush(orderNo, subOrderNo, userId);
        log.info(result);
        return ServerResponse.createBySuccess("发送推送成功");
    }

    private String phoneMsgPush(String orderNo, String subOrderNo, Integer userId){
        EnvUtil envUtil = new EnvUtil();
        String url = envUtil.getPreUrl("hCloud");
        Map map = new HashMap();
        SysUser user = userMapper.selectByPrimaryKey(userId);
        if(user.getPhone() == null) {
            return "没有手机号";
        }
        map.put("mobile", user.getPhone());
        map.put("orderNo", orderNo);
        map.put("subOrderNo", subOrderNo);
        map.put("time", new Date().toLocaleString());
        String s = HttpClientUtil.doGetWithParam(url + "/admin/ncFinishMsg", map);

        return s;
    }
}
